package com.yicong.ants.activity

import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import android.widget.ImageView
import com.blankj.utilcode.util.BarUtils
import com.bumptech.glide.Glide
import com.cchao.simplelib.core.Router
import com.cchao.simplelib.model.event.CommonEvent
import com.cchao.simplelib.ui.activity.BaseActivity
import com.yicong.ants.Constants
import com.yicong.ants.R
import com.yicong.ants.manager.BusinessHelper
import com.yicong.ants.manager.ad.AdManager
import com.yicong.ants.manager.ad.EventHelper
import com.yicong.ants.manager.business.Dialogs
import com.yicong.ants.ui.main.MainConfigActivity
import com.yicong.ants.utils.InitUtil
import com.yicong.ants.viewmodel.AppStartViewModel
import com.zx.sdk.ZxSDK
import java.util.Random

/**
 *启动页Activity
 */
class AppStartActivity : BaseActivity() {
    override fun onEvent(event: CommonEvent) {
        super.onEvent(event)
        when (event.code) {
            Constants.Event.NO_AD_FINAL -> {
                jumpWhenCanClick()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 全屏显示
        BarUtils.transparentStatusBar(this)
        setContentView(R.layout.splash_activity)
        // 监听开屏页背景数据
        AppStartViewModel.observeSplashImages { splashImages ->
            val splashIv = findViewById<ImageView>(R.id.bgIv)
            if (splashImages?.isNotEmpty() == true) {// 开屏背景不为空则随机显示一张
                val url: String = splashImages[Random().nextInt(splashImages.size)]
                Glide.with(this)
                    .load(url)
                    .error(R.drawable.start_bg_top_big)
                    .onlyRetrieveFromCache(true)
                    .into(splashIv)
            } else {// 开屏背景为空则显示默认
                splashIv.setImageResource(R.drawable.start_bg_top_big)
            }
        }
        // 监听隐私协议同意状态
        AppStartViewModel.observePrivacyAgreeState { agreed ->
            if (agreed) {// 已同意则初始化SDK，加载App配置和开屏广告
                InitUtil.init(this)
                BusinessHelper.loadIndexConfig(null)
                AdManager.preloadAndShowSplash(this, findViewById(R.id.adFl))
            } else {// 未同意则弹出隐私协议对话框
                Dialogs.showPrivacyAllow(this) {
                    AppStartViewModel.agreePrivacy()
                }
            }
        }
        // 监听广告显示状态
        AppStartViewModel.observeAdState { state ->
            when (state) {
                AdManager.State.SHOWN -> {// 如果广告显示则让状态栏变黑
                    BarUtils.setStatusBarColor(this, Color.BLACK)
                    BarUtils.setStatusBarLightMode(this, false)
                }

                AdManager.State.DISMISSED -> {// 如果广告消失(计时结束或者点击跳过)则进入主界面
                    jumpWhenCanClick()
                }

                AdManager.State.CLICKED -> {
                    canJumpImmediately = true
                }

                else -> {}
            }
        }
        AppStartViewModel.start()
    }

    /**
     *进入主界面
     */
    private fun startMainActivity() {
        if (isPause
            || AppStartViewModel.adState == AdManager.State.SHOWN
            || AppStartViewModel.adState == AdManager.State.COMPLETE
        ) {// 如果广告已经显示则不进入主界面直到广告消失
            return
        }
        AppStartViewModel.adState = AdManager.State.COMPLETE
        Router.turnTo(this, MainConfigActivity::class.java).start()
        EventHelper.reportEvent("app_start")
        finish()
    }

    /**
     * 开屏页一定要禁止用户对返回按钮的控制，否则将可能导致用户手动退出了App而广告无法正常曝光和计费
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        ZxSDK.destroySplash(this, false)
        super.onDestroy()
    }

    var canJumpImmediately = false

    private fun jumpWhenCanClick() {
        if (canJumpImmediately) {
            startMainActivity()
        } else {
            canJumpImmediately = true
        }
    }

    override fun onResume() {
        super.onResume()
        isPause = false
        if (canJumpImmediately) {
            jumpWhenCanClick()
        }
        canJumpImmediately = true
    }

    private var isPause = false
    override fun onPause() {
        super.onPause()
        isPause = true
    }
}